import colorsys
import glob
import os
import tkinter as tk 
from tkinter import messagebox
from PIL import Image, ImageTk, ImageDraw, ImageGrab
import keyboard
from tkinter import ttk
import cv2
import numpy as np
from natsort import natsorted
#import ttkbootstrap as ttk
#from ttkbootstrap.constants import *


def find_png_files(directory):
    png_files = glob.glob(os.path.join(directory, '**', '*.png'), recursive=True)
    png_files = natsorted(png_files)
    return png_files
def create_window(parent=None):
    # 创建窗口
    if parent is None:
        root = tk.Tk()
    else:
        root = tk.Toplevel(parent)
    #root = tk.Tk()
    root.title("序列帧修改器")
    root.config(bg="grey")
    root.geometry("1800x1000")

    # background_image = Image.open("D:/Users/admin/Downloads/composite/body_output/50001_ATTACK_0/0.png")
    # background_photo = ImageTk.PhotoImage(background_image)
    # canvas.
    # 暂停修改--将index保持不动，一直重复刷同一帧

    global offX, offY
    offX = 60
    offY = 50
    # lf = ttk.Labelframe(text="资源目录", width=100, height=60)
    # lf.place(x=0, y=0, width=300, height=400)
    #
    # lf = ttk.Labelframe(text="指定加载", width=120, height=60)
    # lf.place(x=320, y=0, width=230, height=400)
    #
    # lf = ttk.Labelframe(text="其它操作", width=220, height=60)
    # lf.place(x=580, y=0, width=270, height=400)

    tk.Label(root,text="请输入文件夹路径",bg='green').place(x=offX,y=2)
    tk.Label(root,text="勾选复选框启用锚点修改功能",bg='green').place(x=offX,y=20)

    check_var = tk.IntVar()
    check_var1 = tk.IntVar()
    check_var2 = tk.IntVar()
    check_var3 = tk.IntVar()
    check_var4 = tk.IntVar()
    check_var5 = tk.IntVar()
    def check_status():
        if check_var.get():
            return 'on'
        else:
            return 'off'

    def check_status1():
        if check_var1.get():
            return 'on'
        else:
            return 'off'

    def check_status2():
        if check_var2.get():
            return 'on'
        else:
            return 'off'
    def check_status3():
        if check_var3.get():
            return 'on'
        else:
            return 'off'

    def check_status4():
        if check_var4.get():
            return 'on'
        else:
            return 'off'

    def check_status5():
        if check_var5.get():
            return 'on'
        else:
            return 'off'

    #输入框一
    entry_var = tk.StringVar()
    entry_path = tk.Entry(root, textvariable=entry_var)
    tk.Label(root, text="路径一", bg='green').place(x=offX, y=offY)
    check_anchor = tk.Checkbutton(root,variable=check_var).place(x=offX + 200,y=offY - 3)
    entry_path.place(x=offX+50,y=offY)

    tk.Label(root,text="请输入模型ID或模型ID具体动作",bg='green').place(x=offX+300,y=20)
    entry_role = tk.StringVar()
    entry_rolename = tk.Entry(root, textvariable=entry_role)
    entry_rolename.place(x=offX+300, y= offY)
    #输入框二
    entry_var1 = tk.StringVar()
    tk.Label(root, text="路径二", bg='green').place(x=offX, y=offY+113)
    entry_path1 = tk.Entry(root, textvariable=entry_var1)
    check_anchor1 = tk.Checkbutton(root,variable=check_var1).place(x=offX + 200,y=offY +110)
    entry_path1.place(x=offX+50,y=offY+113)

    tk.Label(root,text="请输入技能ID",bg='green').place(x=offX +300,y=offY + 85)
    entry_skill = tk.StringVar()
    entry_skillname = tk.Entry(root, textvariable=entry_skill)
    entry_skillname.place(x=offX + 300, y= offY + 113)
    #输入框三
    entry_var2 = tk.StringVar()
    entry_path2 = tk.Entry(root, textvariable=entry_var2)
    tk.Label(root, text="路径三", bg='green').place(x=offX, y=offY + 223)
    check_anchor2 = tk.Checkbutton(root,variable=check_var2).place(x=offX + 200,y=offY +220)
    entry_path2.place(x=offX+50,y=offY+223)

    tk.Label(root,text="请输入武器ID或武器ID具体动作",bg='green').place(x=offX +300,y=offY + 195)
    entry_wuqi = tk.StringVar()
    entry_wuqiname = tk.Entry(root, textvariable=entry_wuqi)
    entry_wuqiname.place(x=offX +300, y= offY + 223)

    tk.Label(root, text="路径一缩放勾选", bg='green').place(x=offX, y=offY + 80)
    check_anchor3 = tk.Checkbutton(root, variable=check_var3).place(x=offX + 100, y=offY + 80)
    tk.Label(root, text="路径二缩放勾选", bg='green').place(x=offX, y=offY + 190)
    check_anchor4 = tk.Checkbutton(root, variable=check_var4).place(x=offX + 100, y=offY + 190)
    tk.Label(root, text="路径三缩放勾选", bg='green').place(x=offX, y=offY + 300)
    check_anchor5 = tk.Checkbutton(root, variable=check_var5).place(x=offX + 100, y=offY + 300)

    #切换指定ID角色
    def change_role():
        global role_button, role_name, directory_type,cur_frame_index
        role_name = entry_role.get()
        directory_type = []
        #index = 0
        for item in all_directory_type:
            for name in item:
                if role_name in name:
                    directory_type.append(name)
                    #cur_directory_type_index = index
                    #return
            #index+=1
        load_images_from_directory1()
        cur_frame_index = 0
    #切换指定ID技能
    def change_skill():
        global skill_button, skill_name,directory_type1,cur_frame_index
        skill_name = entry_skill.get()
        directory_type1 = []
        #index = 0
        for item in all_directory_type1:
            for name in item:
                if skill_name in name:
                    #cur_directory_type_index1 = index
                    directory_type1.append(name)
                    #return
            #index+=1
        load_images_from_directory2()
        cur_frame_index = 0
    #切换指定ID武器
    def change_wuqi():
        global wuqi_button, wuqi_name, directory_type2,cur_frame_index
        wuqi_name = entry_wuqi.get()
        directory_type2 = []
        #index = 0
        for item in all_directory_type2:
            for name in item:
                if wuqi_name in name:
                    #cur_directory_type_index2 = index
                    directory_type2.append(name)
                    #return
            #index+=1
        load_images_from_directory3()
        cur_frame_index = 0

    role_button = tk.Button(root, text="加载指定ID模型", command= change_role,bg='skyblue').place(x=offX+300, y= offY+40 )
    skill_button = tk.Button(root, text="加载指定ID技能", command= change_skill,bg='red').place(x=offX + 300, y= offY + 153)
    wuqi_name= tk.Button(root, text="加载指定ID武器", command= change_wuqi,bg='orange').place(x=offX + 300, y= offY + 263)

    global image_frames,image_frames1, image_frames2, image_frames3, cur_frame_index, cur_directory_type_index,input_x, input_y
    global input_x_value,input_y_value,monster_image,image_dic,image_dic1,image_dic2,image_on_canvas,image_cur_canvas,scale_value,min_x,max_x,min_y,max_y,frame
    input_x = 0
    input_y = 0
    input_x_value = 0
    input_y_value = 0
    image_frames = []
    image_frames1 = []
    image_frames2 = []
    image_frames3 = []
    cur_directory_type_index = 0
    cur_frame_index = 0
    coordinates=[(0,-30),(60,-30),(60,0),(60,30),(0,30),(-60,30),(-60,0),(-60,-30)]
    monster_image=[]
    drag_data = {"x": 0, "y": 0, " dragging": False}
    image_dic = {}
    image_dic1 = {}
    image_dic2 = {}
    image_on_canvas = None
    image_cur_canvas = None
    scale_value=1
    min_x=0
    max_x=0
    min_y = 0
    max_y = 0
    frame=0
    # 从目录加载图片
    def load_images_from_directory():
        global image_frames,image_frames1, image_frames2,image_frames3,cur_frame_index, cur_directory_type_index,image_dic
        image_paths = []
        for i, d in enumerate(all_directory_type[cur_directory_type_index]):
            image_paths.extend(find_png_files(image_frames_path + "/" + d))

        if not image_paths:
            messagebox.showerror("Error", "目录一没有图片文件")

        if image_frames_path1 != '':
            image_paths1 = []
            for i, d in enumerate(all_directory_type1[cur_directory_type_index1]):
                image_paths1.extend(find_png_files(image_frames_path1 + "/" + d))
            #image_frames1 = [Image.open(path) for path in image_paths1]

            index = -1
            prev_suffix = ""

            for path in image_paths1:
                suffix = os.path.dirname(path)

                if suffix == prev_suffix and index != -1:
                    image_dic1[index].append(Image.open(path))
                else:
                    index += 1
                    image_dic1[index] = [Image.open(path)]
                    prev_suffix = suffix
            image_frames1 = image_dic1[0]

        if image_frames_path2 != '':
            image_paths2 = []
            for i, d in enumerate(all_directory_type2[cur_directory_type_index2]):
                image_paths2.extend(find_png_files(image_frames_path2 + "/" + d))
            #image_frames2 = [Image.open(path) for path in image_paths2]

            index = -1
            prev_suffix = ""

            for path in image_paths2:
                suffix = os.path.dirname(path)

                if suffix == prev_suffix and index != -1:
                    image_dic2[index].append(Image.open(path))
                else:
                    index += 1
                    image_dic2[index] = [Image.open(path)]
                    prev_suffix = suffix
            image_frames2 = image_dic2[0]

        cur_frame_index = 0
        #image_frames = [Image.open(path) for path in image_paths]
        index = -1
        prev_suffix = ""

        for path in image_paths:
            suffix = os.path.dirname(path)

            if suffix == prev_suffix and index != -1:
                image_dic[index].append(Image.open(path))
            else:
                index += 1
                image_dic[index] = [Image.open(path)]
                prev_suffix = suffix
        image_frames=image_dic[0]

        reset_window()

        # 从目录加载指定动作图片
    def load_images_from_directory1():
        global image_frames,cur_frame_index, cur_directory_type_index, directory_type
        image_paths = []
        for i, d in enumerate(directory_type):
            image_paths.extend(find_png_files(image_frames_path + "/" + d))
        if not image_paths:
            messagebox.showerror("Error", "目录一没有图片文件")
        cur_frame_index = 0
        image_frames = [Image.open(path) for path in image_paths]
        reset_window()

    def load_images_from_directory2():
        global image_frames1,cur_frame_index,directory_type1
        if image_frames_path1 != '' :
            image_paths1 = []
            for i, d in enumerate(directory_type1):
                image_paths1.extend(find_png_files(image_frames_path1 + "/" + d))
            image_frames1 = [Image.open(path) for path in image_paths1]
            cur_frame_index = 0
            reset_window()

    def load_images_from_directory3():
        global image_frames2,cur_frame_index,directory_type2
        if image_frames_path2 != '':
            image_paths2 = []
            for i, d in enumerate(directory_type2):
                image_paths2.extend(find_png_files(image_frames_path2 + "/" + d))
            image_frames2 = [Image.open(path) for path in image_paths2]
            cur_frame_index = 0
            reset_window()


    # 获取输入路径
    def get_input_path():
        global image_frames, last_button, next_button, image_frames_path, image_frames_path1,image_frames_output_path, image_frames_output_path1
        global all_directory_type,all_directory_type1, cur_directory_type_index,cur_directory_type_index1,input_x,input_y
        input_x=0
        input_y=0

        #路径一
        all_directory_type = []
        cur_directory_type_index = 0
        image_frames_path = entry_var.get().replace("\\", "/")
        if image_frames_path != '':
            image_frames_output_path = image_frames_path + "_output"
            all_directory = [d for d in os.listdir(image_frames_path) if os.path.isdir(os.path.join(image_frames_path, d))]
            dir_name = ""
            for i, d in enumerate(all_directory):
                net_dir_name = os.path.basename(d)
                if dir_name.rsplit("_",1)[0] == net_dir_name.rsplit("_",1)[0]:
                    all_directory_type[-1].append(net_dir_name)
                else:
                    dir_name = net_dir_name
                    all_directory_type.append([dir_name])

        if not all_directory_type:
            messagebox.showerror("Error", "路径一没有目录")
            #return
        #路径二
        all_directory_type1 = []
        cur_directory_type_index1 = 0
        image_frames_path1 = entry_var1.get().replace("\\", "/")
        if image_frames_path1 != '':
            image_frames_output_path1 = image_frames_path1 + "_output"
            all_directory1 = [d for d in os.listdir(image_frames_path1) if os.path.isdir(os.path.join(image_frames_path1, d))]
            dir_name1 = ""
            for i, d in enumerate(all_directory1):
                net_dir_name1 = os.path.basename(d)
                if dir_name1.rsplit("_",1)[0] == net_dir_name1.rsplit("_",1)[0]:
                    all_directory_type1[-1].append(net_dir_name1)
                else:
                    dir_name1 = net_dir_name1
                    all_directory_type1.append([dir_name1])

        #路径三
        global all_directory_type2,cur_directory_type_index2,image_frames_path2,image_frames_output_path2
        all_directory_type2 = []
        cur_directory_type_index2 = 0
        image_frames_path2 = entry_var2.get().replace("\\", "/")
        if image_frames_path2 != '':
            image_frames_output_path2 = image_frames_path2 + "_output"
            all_directory2 = [d for d in os.listdir(image_frames_path2) if os.path.isdir(os.path.join(image_frames_path2, d))]
            dir_name2 = ""
            for i, d in enumerate(all_directory2):
                net_dir_name2 = os.path.basename(d)
                if dir_name2.rsplit("_",1)[0] == net_dir_name2.rsplit("_",1)[0]:
                    all_directory_type2[-1].append(net_dir_name2)
                else:
                    dir_name2 = net_dir_name2
                    all_directory_type2.append([dir_name2])

        if (image_frames_path1 and image_frames_path==image_frames_path1
                or image_frames_path2 and image_frames_path==image_frames_path2
                or image_frames_path2 and image_frames_path1==image_frames_path2):
            show_info()
            return
        load_images_from_directory()


    get_input_button = tk.Button(root, text="加载图片", command=get_input_path,bg='skyblue')
    get_input_button.place(x=offX+1100,y=offY)

    def show_info():
        messagebox.showinfo("提示", "图片路径不可一致")

    #按钮，上下切换图片资源一
    def btn_last_directory():
        global cur_directory_type_index,cur_directory_type_index1
        if cur_directory_type_index <= 0:
            messagebox.showerror("Error", "没有了")
            return
        cur_directory_type_index -= 1
        load_images_from_directory()

    def btn_next_directory():
        global cur_directory_type_index
        if cur_directory_type_index >= len(all_directory_type)-1:
            messagebox.showerror("Error", "没有了")
            return
        cur_directory_type_index += 1
        load_images_from_directory()

    last_button = tk.Button(root, text="上一个", command=btn_last_directory)
    last_button.place(x=offX + 10,y=offY+40)
    next_button = tk.Button(root, text="下一个", command=btn_next_directory)
    next_button.place(x=offX+90,y=offY+40)

    #按钮，上下切换图片资源二
    global last_button1,next_button1
    def btn_last_directory1():
        global cur_directory_type_index1
        if cur_directory_type_index1 <= 0:
            messagebox.showerror("Error", "没有了")
            return
        cur_directory_type_index1 -= 1
        load_images_from_directory()

    def btn_next_directory1():
        global cur_directory_type_index1
        if cur_directory_type_index1 >= len(all_directory_type1)-1:
            messagebox.showerror("Error", "没有了")
            return
        cur_directory_type_index1 += 1
        load_images_from_directory()

    last_button1 = tk.Button(root, text="上一个", command=btn_last_directory1)
    last_button1.place(x=offX +10,y=offY+153)
    next_button1 = tk.Button(root, text="下一个", command=btn_next_directory1)
    next_button1.place(x=offX+90,y=offY+153)

    #按钮，上下切换图片资源三
    global last_button2,next_button2
    def btn_last_directory2():
        global cur_directory_type_index2
        if cur_directory_type_index2 <= 0:
            messagebox.showerror("Error", "没有了")
            return
        cur_directory_type_index2 -= 1
        load_images_from_directory()

    def btn_next_directory2():
        global cur_directory_type_index2
        if cur_directory_type_index2 >= len(all_directory_type2)-1:
            messagebox.showerror("Error", "没有了")
            return
        cur_directory_type_index2 += 1
        load_images_from_directory()

    last_button1 = tk.Button(root, text="上一个", command=btn_last_directory2)
    last_button1.place(x=offX +10,y=offY+263)
    next_button1 = tk.Button(root, text="下一个", command=btn_next_directory2)
    next_button1.place(x=offX+90,y=offY+263)


    #图像绘制位置坐标
    canvas = tk.Canvas(root, width=800, height=800, bg="gray")
    canvas.place(x=offX+880,y=offY+50)

    # 重置窗口
    def reset_window():
        global image_max_width, image_max_height, canvas_width, canvas_height, center_x, center_y, cur_frame_index
        image_max_width = 0
        image_max_height = 0
        canvas_width = 800
        canvas_height = 800
        center_x = 0
        center_y = 0
        cur_frame_index = 0
        for i, img in enumerate(image_frames):
            image_max_width = max(image_max_width, img.width)
            image_max_height = max(image_max_height, img.height)

        root_width = max(canvas_width, image_max_width)
        root_height = max(canvas_height, image_max_height)
        #处理大图
        #root.geometry(f"{root_width}x{root_height}")
        #root.geometry("1800x1000")
        canvans_width = max(canvas_width,image_max_width)
        canvans_height = max(canvas_height,image_max_height)
        canvas.config(width=canvans_width, height=canvans_height)
        center_x = canvas_width / 2
        center_y = canvas_height / 2
    #获取输出尺寸
    def get_out_size():
        global max_x, min_x, max_y, min_y
        offset_width=0
        offset_height=0
        if input_x + max_x > image_max_width:
            offset_width =input_x+max_x- image_max_width
        if input_x+min_x<0:
            offset_width=input_x+min_x
        if input_y + max_y > image_max_height:
            offset_height =input_y+max_y-image_max_height
        if input_y+min_y<0:
            offset_height=input_y+min_y
        return offset_width,offset_height

    def on_image_click_down_All():
        global speed, root_after, input_x, input_y, max_x, min_x, max_y, min_y,all_directory_type
        width, min_x, max_x = get_pixels_width()
        height, min_y, max_y = get_pixels_height()
        offset_width, offset_height = get_out_size()
        if check_status() == 'on':

            offset_x = int(input_x)
            offset_y = int(input_y)

            new_image_width = image_max_width + abs(offset_width * 2)
            new_image_height = image_max_height + abs(offset_height * 2)

            image_paths = []
            image_all = []
            for i, d in enumerate(all_directory_type):
                for j ,m in enumerate(d):
                    image_paths.extend(find_png_files(image_frames_path + "/" + m))

            for path in image_paths:
                image_all.append(Image.open(path))

            for i, img in enumerate(image_all):
                new_image_path = img.filename.replace("\\", "/")
                new_image = Image.new("RGBA", (int(new_image_width), int(new_image_height)))
                start_x = int(new_image_width / 2 - img.width / 2 + offset_x)
                start_y = int(new_image_height / 2 - img.height / 2 + offset_y)
                new_image.paste(img, (start_x, start_y, start_x + img.width, start_y + img.height))

                if not new_image_path.startswith(image_frames_output_path):
                    new_image_path = new_image_path.replace(image_frames_path, image_frames_output_path)
                if not os.path.exists(os.path.dirname(new_image_path)):
                    os.makedirs(os.path.dirname(new_image_path))
                new_image.save(new_image_path)

            reset_window()

        if check_status1() == 'on':
            offset_x = int(input_x)
            offset_y = int(input_y)
            new_image_width = image_max_width + abs(offset_width * 2)
            new_image_height = image_max_height + abs(offset_height * 2)

            image_paths1 = []
            image_all1 = []
            for i, d in enumerate(all_directory_type1):
                for j, m in enumerate(d):
                    image_paths1.extend(find_png_files(image_frames_path1 + "/" + m))

            for path in image_paths1:
                image_all1.append(Image.open(path))

            for i, img in enumerate(image_all1):
                new_image_path1 = img.filename.replace("\\", "/")
                new_image = Image.new("RGBA", (int(new_image_width), int(new_image_height)))
                start_x = int(new_image_width / 2 - img.width / 2 + offset_x)
                start_y = int(new_image_height / 2 - img.height / 2 + offset_y)
                new_image.paste(img, (start_x, start_y, start_x + img.width, start_y + img.height))

                if not new_image_path1.startswith(image_frames_output_path1):
                    new_image_path1 = new_image_path1.replace(image_frames_path1, image_frames_output_path1)
                if not os.path.exists(os.path.dirname(new_image_path1)):
                    os.makedirs(os.path.dirname(new_image_path1))
                new_image.save(new_image_path1)

        if check_status2() == 'on':
            offset_x = int(input_x)
            offset_y = int(input_y)
            new_image_width = image_max_width + abs(offset_width * 2)
            new_image_height = image_max_height + abs(offset_height * 2)

            image_paths2 = []
            image_all2 = []
            for i, d in enumerate(all_directory_type2):
                for j, m in enumerate(d):
                    image_paths2.extend(find_png_files(image_frames_path2 + "/" + m))

            for path in image_paths2:
                image_all2.append(Image.open(path))

            for i, img in enumerate(image_all2):
                new_image_path2 = img.filename.replace("\\", "/")
                new_image = Image.new("RGBA", (int(new_image_width), int(new_image_height)))
                start_x = int(new_image_width / 2 - img.width / 2 + offset_x)
                start_y = int(new_image_height / 2 - img.height / 2 + offset_y)
                new_image.paste(img, (start_x, start_y, start_x + img.width, start_y + img.height))

                if not new_image_path2.startswith(image_frames_output_path2):
                    new_image_path2 = new_image_path2.replace(image_frames_path2, image_frames_output_path2)
                if not os.path.exists(os.path.dirname(new_image_path2)):
                    os.makedirs(os.path.dirname(new_image_path2))
                new_image.save(new_image_path2)

        #input_x = 0
        #input_y = 0
    # 鼠标左键点击
    def on_image_click_down():
        global speed , root_after,input_x, input_y,max_x,min_x,max_y,min_y
        width, min_x, max_x = get_pixels_width()
        height, min_y, max_y = get_pixels_height()
        offset_width, offset_height = get_out_size()
        if check_status() == 'on':
            # root_after = root.after(speed, update_frame)
            # offset_x = int(event.x - center_x)
            # offset_y = int(event.y - center_y)

            offset_x = int(input_x)
            offset_y = int(input_y)


            new_image_width = image_max_width + abs(offset_width * 2)
            new_image_height = image_max_height + abs(offset_height * 2)

            # if input_x+max_x>image_max_width or input_x<0 or input_y+max_y>image_max_height or offset_y<0:
            #     if input_x+max_x>image_max_width:
            #         offset_width = image_max_width-input_x
            #     if offset_y+max_y>image_max_height:
            #         offset_height = image_max_height-input_y
            #     new_image_width = image_max_width + abs(offset_width * 2)
            #     new_image_height = image_max_height + abs(offset_height * 2)
            # else:
            #     new_image_width = image_max_width
            #     new_image_height = image_max_height

            for imageList in image_dic.values():
                for i, img in enumerate(imageList):
                    new_image_path = img.filename.replace("\\", "/")
                    new_image = Image.new("RGBA", (int(new_image_width), int(new_image_height)))
                    start_x = int(new_image_width / 2 - img.width / 2 + offset_x)
                    start_y = int(new_image_height / 2 - img.height / 2 + offset_y)
                    new_image.paste(img, (start_x, start_y,start_x + img.width, start_y + img.height))

                    # crop_box = new_image.getbbox() # 剪切图片有效区域
                    # if crop_box:
                    #     crop_x = min(crop_box[0], new_image.width - crop_box[2])
                    #     crop_y = min(crop_box[1], new_image.height - crop_box[3])
                    #     new_image = new_image.crop((crop_x, crop_y, new_image.width - crop_x, new_image.height - crop_y))

                    if not new_image_path.startswith(image_frames_output_path):
                        new_image_path = new_image_path.replace(image_frames_path, image_frames_output_path)
                    if not os.path.exists(os.path.dirname(new_image_path)):
                        os.makedirs(os.path.dirname(new_image_path))
                    new_image.save(new_image_path)
                    #image_frames[i] = Image.open(new_image_path)

            reset_window()

        if check_status1() == 'on':
            # root_after = root.after(speed, update_frame)
            offset_x =  int(input_x)
            offset_y =  int(input_y)
            new_image_width = image_max_width + abs(offset_width*2)
            new_image_height = image_max_height + abs(offset_height*2)

            for imageList in image_dic1.values():
                for i, img in enumerate(imageList):
                    new_image_path1 = img.filename.replace("\\", "/")
                    new_image = Image.new("RGBA", (int(new_image_width), int(new_image_height)))
                    start_x = int(new_image_width / 2 - img.width / 2 + offset_x)
                    start_y = int(new_image_height / 2 - img.height / 2 + offset_y)
                    new_image.paste(img, (start_x, start_y, start_x + img.width, start_y + img.height))

                    # crop_box = new_image.getbbox() # 剪切图片有效区域
                    # if crop_box:
                    #     crop_x = min(crop_box[0], new_image.width - crop_box[2])
                    #     crop_y = min(crop_box[1], new_image.height - crop_box[3])
                    #     new_image = new_image.crop((crop_x, crop_y, new_image.width - crop_x, new_image.height - crop_y))

                    if not new_image_path1.startswith(image_frames_output_path1):
                        new_image_path1 = new_image_path1.replace(image_frames_path1, image_frames_output_path1)
                    if not os.path.exists(os.path.dirname(new_image_path1)):
                        os.makedirs(os.path.dirname(new_image_path1))
                    new_image.save(new_image_path1)
                #image_frames1[i] = Image.open(new_image_path1)

        if check_status2() == 'on':
            # root_after = root.after(speed, update_frame)
            offset_x =  int(input_x)
            offset_y =  int(input_y)
            new_image_width = image_max_width + abs(offset_width*2)
            new_image_height = image_max_height + abs(offset_height*2)
            for imageList in image_dic2.values():
                for i, img in enumerate(imageList):
                    new_image_path2 = img.filename.replace("\\", "/")
                    new_image = Image.new("RGBA", (int(new_image_width), int(new_image_height)))
                    start_x = int(new_image_width / 2 - img.width / 2 + offset_x)
                    start_y = int(new_image_height / 2 - img.height / 2 + offset_y)
                    new_image.paste(img, (start_x, start_y, start_x + img.width, start_y + img.height))

                    # crop_box = new_image.getbbox() # 剪切图片有效区域
                    # if crop_box:
                    #     crop_x = min(crop_box[0], new_image.width - crop_box[2])
                    #     crop_y = min(crop_box[1], new_image.height - crop_box[3])
                    #     new_image = new_image.crop((crop_x, crop_y, new_image.width - crop_x, new_image.height - crop_y))

                    if not new_image_path2.startswith(image_frames_output_path2):
                        new_image_path2 = new_image_path2.replace(image_frames_path2, image_frames_output_path2)
                    if not os.path.exists(os.path.dirname(new_image_path2)):
                        os.makedirs(os.path.dirname(new_image_path2))
                    new_image.save(new_image_path2)
                #image_frames2[i] = Image.open(new_image_path2)

        #input_x = 0
        #input_y = 0

    def on_image_single_click_down():
        global speed, root_after, input_x, input_y, max_x, min_x, max_y, min_y
        width, min_x, max_x = get_pixels_width()
        height, min_y, max_y = get_pixels_height()
        offset_width, offset_height = get_out_size()
        index = int(selected_option.get())
        if check_status() == 'on':

            offset_x = int(input_x)
            offset_y = int(input_y)

            new_image_width = image_max_width + abs(offset_width * 2)
            new_image_height = image_max_height + abs(offset_height * 2)


            imageList = image_dic[index]


            for i, img in enumerate(imageList):
                new_image_path = img.filename.replace("\\", "/")
                new_image = Image.new("RGBA", (int(new_image_width), int(new_image_height)))
                start_x = int(new_image_width / 2 - img.width / 2 + offset_x)
                start_y = int(new_image_height / 2 - img.height / 2 + offset_y)
                new_image.paste(img, (start_x, start_y, start_x + img.width, start_y + img.height))


                if not new_image_path.startswith(image_frames_output_path):
                    new_image_path = new_image_path.replace(image_frames_path, image_frames_output_path)
                if not os.path.exists(os.path.dirname(new_image_path)):
                    os.makedirs(os.path.dirname(new_image_path))
                new_image.save(new_image_path)
                # image_frames[i] = Image.open(new_image_path)

            reset_window()

        if check_status1() == 'on':
            # root_after = root.after(speed, update_frame)
            offset_x = int(input_x)
            offset_y = int(input_y)
            new_image_width = image_max_width + abs(offset_width * 2)
            new_image_height = image_max_height + abs(offset_height * 2)

            imageList = image_dic1[index]


            for i, img in enumerate(imageList):
                new_image_path1 = img.filename.replace("\\", "/")
                new_image = Image.new("RGBA", (int(new_image_width), int(new_image_height)))
                start_x = int(new_image_width / 2 - img.width / 2 + offset_x)
                start_y = int(new_image_height / 2 - img.height / 2 + offset_y)
                new_image.paste(img, (start_x, start_y, start_x + img.width, start_y + img.height))

                if not new_image_path1.startswith(image_frames_output_path1):
                    new_image_path1 = new_image_path1.replace(image_frames_path1, image_frames_output_path1)
                if not os.path.exists(os.path.dirname(new_image_path1)):
                    os.makedirs(os.path.dirname(new_image_path1))
                new_image.save(new_image_path1)

        if check_status2() == 'on':
            # root_after = root.after(speed, update_frame)
            offset_x = int(input_x)
            offset_y = int(input_y)
            new_image_width = image_max_width + abs(offset_width * 2)
            new_image_height = image_max_height + abs(offset_height * 2)

            imageList = image_dic2[index]


            for i, img in enumerate(imageList):
                new_image_path2 = img.filename.replace("\\", "/")
                new_image = Image.new("RGBA", (int(new_image_width), int(new_image_height)))
                start_x = int(new_image_width / 2 - img.width / 2 + offset_x)
                start_y = int(new_image_height / 2 - img.height / 2 + offset_y)
                new_image.paste(img, (start_x, start_y, start_x + img.width, start_y + img.height))

                if not new_image_path2.startswith(image_frames_output_path2):
                    new_image_path2 = new_image_path2.replace(image_frames_path2, image_frames_output_path2)
                if not os.path.exists(os.path.dirname(new_image_path2)):
                    os.makedirs(os.path.dirname(new_image_path2))
                new_image.save(new_image_path2)

        #input_x = 0
        #input_y = 0
    # 鼠标指针样式
    def on_canvas_enter(event):
        event.widget.config(cursor="tcross")
    def on_canvas_leave(event):
        event.widget.config(cursor="")

    # 鼠标事件处理
    def on_mouse_press(event):
        drag_data["x"] = event.x
        drag_data["y"] = event.y
        drag_data["dragging"] = True

    def on_mouse_release(event):
        drag_data["dragging"] = False

    def on_mouse_move(event):
        global input_x, input_y, input_x_value, input_y_value
        global image_on_canvas
        if drag_data["dragging"]:
            dx = event.x - drag_data["x"]
            dy = event.y - drag_data["y"]
            drag_data["x"] = event.x
            drag_data["y"] = event.y
            if check_status() == 'on' or check_status1() == 'on' or check_status2() == 'on':
                if (isplay):
                    input_x += dx
                    input_y += dy
                else:
                    input_x += dx
                    input_y += dy
                    canvas.move(image_on_canvas, dx, dy)


    # canvas.bind("<Button-1>", on_image_click_down)
    canvas.bind("<Enter>", on_canvas_enter)
    canvas.bind("<Leave>", on_canvas_leave)
    canvas.bind("<ButtonPress-1>", on_mouse_press)
    canvas.bind("<ButtonRelease-1>", on_mouse_release)
    canvas.bind("<B1-Motion>", on_mouse_move)

    global speed, root_after
    speed = 100

    #暂停,继续，重置，调速方法
    entry_speed = tk.StringVar()
    entry_speedvalue = tk.Entry(root,textvariable=entry_speed,width= 7)
    entry_speedvalue.place(x=offX+800,y=offY + 350)

    entry_frame = tk.StringVar()
    entry_framevalue = tk.Entry(root, textvariable=entry_frame, width=7)
    entry_framevalue.place(x=offX + 800, y=offY + 640)

    def left_right():
        global min_x,max_x,input_x
        global image_on_canvas
        if check_status() == 'on' or check_status1() == 'on' or check_status2() == 'on':
            width, min_x, max_x = get_pixels_width()
            input_x = 0
            print(max_x, min_x)
            offset = width / 2 - (max_x + min_x) / 2
            input_x += offset

    def get_pixels_width():
        global image_on_canvas
        img = image_frames[cur_frame_index]
        pixels = img.load()  # 像素访问对象
        width, height = img.size

        min_x = width  # 初始化为最大值
        max_x = -1  # 初始化为最小值
        for y in range(height):
            for x in range(width):
                r, g, b, a = pixels[x, y]
                if a != 0:  # 非透明像素
                    if x < min_x:
                        min_x = x
                    if x > max_x:
                        max_x = x
        if min_x > max_x:
            # 没有找到非透明像素
            return None, None
        return width,min_x,max_x

    def up_down():
        global min_y, max_y, input_y
        global image_on_canvas
        if check_status() == 'on' or check_status1() == 'on' or check_status2() == 'on':
            height, min_y, max_y = get_pixels_height()
            input_y = 0
            print(max_y, min_y)
            offset = height / 2 - (max_y + min_y) / 2
            input_y += offset

    def get_pixels_height():
        global image_on_canvas
        img = image_frames[cur_frame_index]
        pixels = img.load()  # 像素访问对象
        width, height = img.size

        min_y = height  # 初始化为最大值
        max_y = -1  # 初始化为最小值
        for y in range(height):
            for x in range(width):
                r, g, b, a = pixels[x, y]
                if a != 0:  # 非透明像素
                    if y < min_y:
                        min_y = y
                    if y > max_y:
                        max_y = y
        if min_y > max_y:
            # 没有找到非透明像素
            return None, None
        return height,min_y,max_y

    def set_speed_play():
        global stop_button, continue_button, first_frame_button, speed_button,speed
        speed = entry_speed.get()

    def set_frame_play():
        global stop_button, continue_button, first_frame_button, speed_button,frame
        frame = int(entry_frame.get())

    global isplay
    isplay = True
    def stop_play():
        global image_on_canvas,image_cur_canvas
        global root_after
        global speed,isplay

        # if(isplay):
        #     root.after_cancel(root_after)
        # else:
        #     root_after = root.after(speed, update_frame)
        isplay = not isplay

        if check_status() == 'on' and not isplay:
            image_on_canvas=canvas.create_image(center_x + int(input_x), center_y + int(input_y), anchor=tk.CENTER, image=photo_image)
            canvas.itemconfigure(image_cur_canvas, state='hidden')
        else:
            canvas.itemconfigure(image_on_canvas, state='hidden')
            canvas.itemconfigure(image_cur_canvas, state='normal')
        if image_frames_path1 != '':
            if check_status1() == 'on' and not isplay:
                image_on_canvas=canvas.create_image(center_x + int(input_x), center_y + int(input_y), anchor=tk.CENTER,image=photo_image1)
                canvas.itemconfigure(image_cur_canvas, state='hidden')
            else:
                canvas.itemconfigure(image_on_canvas, state='hidden')
                canvas.itemconfigure(image_cur_canvas, state='normal')
        if image_frames_path2 != '':
            if check_status2() == 'on' and not isplay:
                canvas.itemconfigure(image_cur_canvas, state='hidden')
                image_on_canvas=canvas.create_image(center_x + int(input_x), center_y + int(input_y), anchor=tk.CENTER,image=photo_image2)
            else:
                canvas.itemconfigure(image_on_canvas, state='hidden')
                canvas.itemconfigure(image_cur_canvas, state='normal')

    def continue_play():
        global root_after
        global speed
        root_after = root.after(speed, update_frame)

    def restart_play():
        global cur_frame_index
        cur_frame_index = 0

    stop_button = tk.Button(root, text="左右对齐", command=left_right).place(x=offX + 800, y=offY + 50)
    stop_button = tk.Button(root, text="上下对齐", command=up_down).place(x=offX + 800, y=offY + 100)
    stop_button = tk.Button(root, text="暂停/继续", command= stop_play).place(x=offX+800,y=offY + 200)
    stop_button = tk.Button(root, text="继续播放", command= continue_play).place(x=offX+800,y=offY + 250)
    stop_button = tk.Button(root, text="从头播放", command= restart_play).place(x=offX+800,y=offY + 300)
    stop_button = tk.Button(root, text="调整速度", command= set_speed_play).place(x=offX+800,y=offY + 380)
    stop_button = tk.Button(root, text="跳转帧数", command=set_frame_play).place(x=offX + 800, y=offY + 600)

    # 刷新帧
    def update_frame():
        global photo_image, photo_image1,photo_image2,photo_image3,cur_frame_index, root_after,path_index1,image_name
        global input_x, input_y
        global image_on_canvas,image_cur_canvas,frame
        index =int(selected_option.get())
        if image_dic:
            if index >= len(image_dic):
                index=0
            image_frames = image_dic[index]
            #目录一
            if  cur_frame_index >= len(image_frames):
                if index >= len(image_dic1):
                    index = 0
                path_index = len(image_frames) - 1
                image_frame = image_frames[path_index]
            else:
                image_frame = image_frames[cur_frame_index]
            if check_status3() == 'on':
                resized_img = PlayReSizeImage(image_frame.filename, scale_value)
                photo_image = ImageTk.PhotoImage(resized_img)
            else:
                photo_image = ImageTk.PhotoImage(image_frame)
            #目录二
            if image_frames_path1 != '':
                image_frames1 = image_dic1[index]
                if cur_frame_index >= len(image_frames1):
                    path_index1 = len(image_frames1)-1
                    image_frame1 = image_frames1[path_index1]
                else:
                    image_frame1 = image_frames1[cur_frame_index]
                if check_status4() == 'on':
                    resized_img = PlayReSizeImage(image_frame1.filename, scale_value)
                    photo_image1 = ImageTk.PhotoImage(resized_img)
                else:
                    photo_image1 = ImageTk.PhotoImage(image_frame1)
            #目录三
            if image_frames_path2 != '':
                if index >= len(image_dic2):
                    index = 0
                image_frames2 = image_dic2[index]
                if cur_frame_index >= len(image_frames2):
                    path_index2 = len(image_frames2)-1
                    image_frame2 = image_frames2[path_index2]
                else:
                    image_frame2 = image_frames2[cur_frame_index]
                if check_status5() == 'on':
                    resized_img = PlayReSizeImage(image_frame2.filename, scale_value)
                    photo_image2 = ImageTk.PhotoImage(resized_img)
                else:
                    photo_image2 = ImageTk.PhotoImage(image_frame2)


            canvas.delete("all")  # 清除之前的图像
            canvas.create_rectangle(center_x-image_frame.width/2, center_y-image_frame.height/2, center_x+image_frame.width/2, center_y+image_frame.height/2, fill="white", outline="black")
            if monster_image:
                canvas.create_image(monster_x, monster_y, anchor=tk.CENTER, image=monster_image[0])
            if change_hierarchys:
                path1_lower()
            else:
                path2_lower()
            if image_frames_path2 != '':
                if check_status2() == 'on':
                    image_cur_canvas=canvas.create_image(center_x+ int(input_x), center_y + int(input_y), anchor=tk.CENTER, image=photo_image2)
                else :
                    canvas.create_image(center_x, center_y, anchor=tk.CENTER, image=photo_image2)
            canvas.create_line(0, center_y , canvas_width, center_y, fill="red", width=1)
            canvas.create_line(center_x, 0, center_x, canvas_height, fill="red", width=1)
            #显示当前正在播放的人物，技能和武器动画名称
            image_name = image_frame.filename.replace("\\", "/").replace(image_frames_path, "")
            root.title("人物" + image_name)
            length = len(image_frames)
            if image_frames_path1 != '':
                image_name1 = image_frame1.filename.replace("\\", "/").replace(image_frames_path1, "")
                root.title("人物" + image_name + "   技能" + image_name1)
                length = max(len(image_frames),len(image_frames1))
            if image_frames_path2 != '':
                image_name2 = image_frame2.filename.replace("\\", "/").replace(image_frames_path2, "")
                root.title("人物" + image_name + "   技能" + image_name1 + "   武器" + image_name2)
                length = max(len(image_frames),len(image_frames1),len(image_frames2))

            #cur_frame_index = (cur_frame_index + 1) % length  # 循环显示
            if isplay:
                cur_frame_index = (cur_frame_index + 1) % length  # 循环显示
            else:
                cur_frame_index=frame

            #image_on_canvas = canvas.create_image(center_x, center_y, image=photo_image)
        root_after = root.after(speed, update_frame)  # 每100毫秒更新一次

    #路径一置底
    def path1_lower():
        global image_on_canvas, image_cur_canvas,cur_frame_index,scale_value
        if check_status() == 'on':
            image_cur_canvas = canvas.create_image(center_x + int(input_x), center_y + int(input_y), anchor=tk.CENTER,
                                                   image=photo_image)
        else:
            canvas.create_image(center_x, center_y, anchor=tk.CENTER, image=photo_image)
        if image_frames_path1 != '':
            if check_status1() == 'on':
                image_cur_canvas = canvas.create_image(center_x + int(input_x), center_y + int(input_y),
                                                       anchor=tk.CENTER, image=photo_image1)
            else:
                canvas.create_image(center_x, center_y, anchor=tk.CENTER, image=photo_image1)
    # 路径二置底
    def path2_lower():
        global image_on_canvas, image_cur_canvas
        if image_frames_path1 != '':
            if check_status1() == 'on':
                image_cur_canvas = canvas.create_image(center_x + int(input_x), center_y + int(input_y),
                                                               anchor=tk.CENTER, image=photo_image1)
            else:
                canvas.create_image(center_x, center_y, anchor=tk.CENTER, image=photo_image1)
        if check_status() == 'on':
            image_cur_canvas = canvas.create_image(center_x + int(input_x), center_y + int(input_y),
                                                           anchor=tk.CENTER,
                                                           image=photo_image)
        else:
            canvas.create_image(center_x, center_y, anchor=tk.CENTER, image=photo_image)

    def save_canvas_as_image():
        global image_frames, image_frames1,change_hierarchys
        ind = 0

        move_img=[]
        move_img1=[]
        for img_frames in image_dic.values():
            for i, img in enumerate(img_frames):
                move_img.append(img)

        for img_frames1 in image_dic1.values():
            for i, img in enumerate(img_frames1):
                move_img1.append(img)
        index=0
        for image1 in image_dic1.values():
            for i, img in enumerate(image1):
                # 拿到主图
                image_frame = image_dic[ind]
                length = len(image_frame) - 1
                if( i > length):
                    image_frame = image_dic[ind][length]
                else:
                    image_frame = image_dic[ind][i]

                # if( i > length2):
                #     image_frame2 = image_frames1[length2]
                # else:
                #     image_frame2 = image_frames1[i]
                # 获取两张图片的尺寸
                width1, height1 = image_frame.size
                width2, height2 = img.size

                # 找到最大的宽度和高度
                max_width = max(width1, width2)
                max_height = max(height1, height2)

                # 创建一个与较大图片尺寸相同的透明背景
                new_img1 = Image.new("RGBA", (max_width, max_height), (255, 255, 255, 0))
                new_img2 = Image.new("RGBA", (max_width, max_height), (255, 255, 255, 0))

                # 将原图粘贴到新创建的透明背景上，保持居中
                new_img1.paste(image_frame, ((max_width - width1) // 2, (max_height - height1) // 2))
                new_img2.paste(img, ((max_width - width2) // 2, (max_height - height2) // 2))

                # 叠加两张图片，保留透明部分
                if(change_hierarchys):
                    final_image = Image.alpha_composite(new_img1, new_img2)
                else:
                    final_image = Image.alpha_composite(new_img2, new_img1)

                # 保存为文件
                image_name = image_frame.filename.replace("\\", "/").replace(image_frames_path, "")
                file_name = image_name.split("/")[1]
                Path = image_frames_output_path + "/" + file_name + "/" +str(i) + ".png"
                if not os.path.exists(os.path.dirname(Path)):
                    os.makedirs(os.path.dirname(Path))
                final_image.save(Path)
            ind +=1

    # 保存Canvas内容为图片
    save_button = tk.Button(root, text="合并图像", command=save_canvas_as_image).place(x=offX+800,y=offY + 460)
    global change_hierarchys
    change_hierarchys = True
    tk.Label(root,text="路径一置底",bg='green').place(x=offX+800,y=offY + 570)

    def change_hierarchy():
        global change_hierarchys, hierarchy_button
        change_hierarchys = not change_hierarchys
        if(change_hierarchys):
            tk.Label(root,text="路径一置底",bg='green').place(x=offX+800,y=offY + 570)
        else:
            tk.Label(root,text="路径二置底",bg='orange').place(x=offX+800,y=offY + 570)

    hierarchy_button = tk.Button(root, text= "层级切换", command=change_hierarchy).place(x=offX+800,y=560)

    def on_key_event(event):
        global input_x, input_y, input_x_value , input_y_value
        if keyboard.is_pressed('up'):  # 检查是否按下了 '' 键
            input_y -= int(input_y_value)
        if keyboard.is_pressed('down'):
            input_y += int(input_y_value)
        if keyboard.is_pressed('left'):
            input_x -= int(input_x_value)
        if keyboard.is_pressed('right'):
            input_x += int(input_x_value)
            # input_x += input_x
            # print("检测到 right 键！::" + str(input_x))
            # print(f"Key {event.name} was pressed")

    # 注册一个键盘事件
    keyboard.on_press(on_key_event)

    save_change_img_local = tk.Button(root, text= "裁剪图片",command= on_image_click_down,bg="skyblue").place(x=offX + 1320,y=offY)
    save_change_img_local = tk.Button(root, text="裁剪所有图片", command=on_image_click_down_All, bg="skyblue").place(
       x=offX + 1400, y=offY)
    save_change_img_local = tk.Button(root, text="裁剪单独方向动作", command=on_image_single_click_down, bg="skyblue").place(
        x=offX + 1500, y=offY)
    #调整量输入框
    entry_var_change = tk.StringVar()
    entry_path = tk.Entry(root, textvariable=entry_var_change,width=5)
    entry_path.place(x=offX + 1200,y=offY+3)

    entry_var_offset = tk.StringVar()
    entry_path = tk.Entry(root, textvariable=entry_var_offset, width=10)
    entry_path.place(x=offX + 800, y=offY -32)

    entry_var_offsetX = tk.StringVar(value="0")
    entry_path = tk.Entry(root, textvariable=entry_var_offsetX, width=5)
    entry_path.place(x=offX + 800, y=offY +3)

    entry_var_offsetY = tk.StringVar(value="0")
    entry_path = tk.Entry(root, textvariable=entry_var_offsetY, width=5)
    entry_path.place(x=offX + 850, y=offY +3)

    def save_change_input_values():
        global input_x_value, input_y_value
        input_x_value = entry_var_change.get()
        input_y_value = entry_var_change.get()

    def get_offset():
        global input_x, input_y
        value= "X:{},Y:{}".format(input_x, input_y)


        entry_var_offset.set(value)

    def load_offset():
        global input_x, input_y
        input_x = int(entry_var_offsetX.get())
        input_y = int(entry_var_offsetY.get())


    save_change_input_value = tk.Button(root, text= "调整",command= save_change_input_values,bg="skyblue").place(x=offX + 1250,y=offY)
    save_change_input_value = tk.Button(root, text="显示当前偏移量", command=get_offset, bg="skyblue").place(
        x=offX + 900, y=offY-35)
    save_change_input_value = tk.Button(root, text="应用偏移量", command=load_offset,
                                        bg="skyblue").place(
        x=offX + 900, y=offY)

    # ---------------------------------------------------------------------------------------------------------------------------------------------

    #-----------------------------------------------------------------------------------------------------------------------------------------------------------


    def monsterAdd():
        index=int(entry_var_monsterIndex.get())
        index+=1
        entry_var_monsterIndex.set(str(index))

    def monsterMinus():
        index = int(entry_var_monsterIndex.get())
        index -= 1
        entry_var_monsterIndex.set(str(index))

    def loadMonster():
        global monster_x,monster_y
        monsterPath = entry_var_monster.get()
        count=int(entry_var_plaid.get())
        index=int(entry_var_monsterIndex.get())
        if index<=0 or index>8 or monsterPath=='':
            return
        image = Image.open(monsterPath)
        monster_image.clear()
        monster_image.append(ImageTk.PhotoImage(image))
        # 计算 Canvas 的中心位置
        monster_x = center_x+coordinates[index-1][0]*count
        monster_y = center_y+coordinates[index-1][1]*count

    def GetImgScale():
        global scale_value,image_cur_canvas
        scale_value = float(entry_var_scale.get())
        #canvas.itemconfigure(image_cur_canvas, state='hidden')

    #怪物图片输入框
    entry_var_monster = tk.StringVar()
    entry_path = tk.Entry(root, textvariable=entry_var_monster,width=15)
    tk.Label(root,text="请输入怪物图片路径",bg='green').place(x=offX+660,y=12)
    entry_path.place(x=offX + 540,y=offY - 37)

    #怪物位置输入框
    entry_var_monsterIndex = tk.StringVar()
    entry_var_monsterIndex.set(1)
    entry_path = tk.Entry(root, textvariable=entry_var_monsterIndex,width=5)
    tk.Label(root,text="请输入怪物位置",bg='green').place(x=offX+660,y=offY)
    entry_path.place(x=offX + 570,y=offY)
    monsterAdd_button = tk.Button(root, text=" - ", command=monsterMinus)
    monsterAdd_button.place(x=offX + 540,y=offY)
    monsterMinus_button = tk.Button(root, text=" + ", command=monsterAdd)
    monsterMinus_button.place(x=offX+620,y=offY)

    #怪物图片加载
    loadMonster_button = tk.Button(root, text="怪物加载", command=loadMonster)
    loadMonster_button.place(x=offX + 562,y=offY+40)

    #格子数
    entry_var_plaid = tk.StringVar()
    entry_var_plaid.set(1)
    entry_path = tk.Entry(root, textvariable=entry_var_plaid,width=5)
    tk.Label(root,text="请输入格子数量",bg='green').place(x=offX+660,y=offY+80)
    entry_path.place(x=offX + 570,y=offY+80)

    #下拉框
    options = ["0", "1", "2", "3","4", "5", "6", "7"]
    # 创建变量用于存储选中值
    selected_option = tk.StringVar()
    # 创建下拉框
    tk.Label(root, text="模型方向", bg='green').place(x=offX + 800, y=offY + 140)
    combobox = ttk.Combobox(root, textvariable=selected_option,width=5)
    combobox['values'] = options
    combobox['state'] = 'readonly'  # 设置为只读，防止手动输入
    combobox.current(0)  # 默认选中第一个选项
    combobox.place(x=offX + 800,y=offY+160)

    # 图片缩放大小
    entry_var_scale = tk.StringVar()
    entry_path = tk.Entry(root, textvariable=entry_var_scale, width=15)
    tk.Label(root, text="图片缩放大小", bg='green').place(x=offX + 660, y=offY +160)
    entry_path.place(x=offX + 540, y=offY +160)
    Scale_button = tk.Button(root, text="缩放", command=GetImgScale)
    Scale_button.place(x=offX + 540, y=offY +190)

    def PlayReSizeImage(input_image_path, scale_factor):
        # 尝试读取图像
        image = cv2.imread(input_image_path, cv2.IMREAD_UNCHANGED)  # 保留透明度通道
        if image is None:
            print(f"无法读取图像：{input_image_path}")

        # 判断图像是否有Alpha通道
        if image.shape[2] == 4:  # 图像是RGBA格式，包含透明度通道
            bgr_image = image[:, :, :3]  # 只取BGR部分（不包括Alpha通道）
            alpha_channel = image[:, :, 3]  # 获取Alpha通道
        else:
            bgr_image = image
            alpha_channel = None

        # 将图像从 BGR 格式转换为 RGB 格式（因为 OpenCV 使用 BGR，而 PIL 使用 RGB）
        rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB)

        # 使用 OpenCV 的 INTER_CUBIC 插值方法进行放大
        enlarged_image = cv2.resize(rgb_image, (0, 0), fx=scale_factor, fy=scale_factor, interpolation=cv2.INTER_CUBIC)

        if alpha_channel is not None:
            # 对于带有透明度的图像，放大Alpha通道
            enlarged_alpha = cv2.resize(alpha_channel, (0, 0), fx=scale_factor, fy=scale_factor,
                                        interpolation=cv2.INTER_CUBIC)
            # 合并RGB和Alpha通道
            enlarged_image = np.dstack((enlarged_image, enlarged_alpha))

        # 使用 PIL 进一步处理图像
        pil_image = Image.fromarray(enlarged_image)
        return pil_image

    #--------------------------------------------------------------------------------------------------------------------------------------------------

    update_frame()
    root.mainloop()

if __name__ == "__main__":
    create_window(None)
